#include "mainwindow.h"
#include <QWidget>
#include <QListWidgetItem>
#include <QIcon>
#include <QSize>
#include <QMessageBox>
#include <QFileDialog>
#include <QRandomGenerator>
#include <QApplication>
#include <QPalette>
#include <QBrush>
#include <QColor>
#include <QDebug>
#include <QPainter>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    ,m_sceneItem(nullptr)
    ,m_upcloItem(nullptr)
    ,m_downcloItem(nullptr)
    ,m_dressItem(nullptr)
    ,m_shoesItem(nullptr)
    ,m_characterItem(nullptr)
    , m_comboItem(nullptr)  // 初始化合成图项
    , m_showingCombo(false) // 初始化合成图显示状态
{
    setWindowTitle("服饰搭配工具");
    setMinimumSize(1000,700);

    initUI();
    initConnections();
    loadClothes();
    loadOutfitCombos(); // 加载套装组合
    onScene1BtnClicked();
    loadCharacter();
}

MainWindow::~MainWindow(){}


void MainWindow::initUI()
{
    QWidget *centralWidget = new QWidget(this);
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
    setCentralWidget(centralWidget);

    //左侧标签页
    QTabWidget* tabWidget = new QTabWidget;

    m_upcloList = new QListWidget;
    m_upcloList ->setViewMode(QListWidget::IconMode);
    m_upcloList ->setIconSize(QSize(80,80));
    m_upcloList ->setResizeMode(QListWidget::Adjust);
    m_upcloList ->setSpacing(10);
    tabWidget->addTab(m_upcloList,"上衣");

    m_downcloList = new QListWidget;
    m_downcloList->setViewMode(QListWidget::IconMode);
    m_downcloList->setIconSize(QSize(80, 80));
    m_downcloList->setResizeMode(QListWidget::Adjust);
    m_downcloList->setSpacing(10);
    tabWidget->addTab(m_downcloList, "下装");

    m_shoesList = new QListWidget;
    m_shoesList->setViewMode(QListWidget::IconMode);
    m_shoesList->setIconSize(QSize(80, 80));
    m_shoesList->setResizeMode(QListWidget::Adjust);
    m_shoesList->setSpacing(10);
    tabWidget->addTab(m_shoesList, "鞋子");

    m_dressList = new QListWidget;
    m_dressList->setViewMode(QListWidget::IconMode);
    m_dressList->setIconSize(QSize(80, 80));
    m_dressList->setResizeMode(QListWidget::Adjust);
    m_dressList->setSpacing(10);
    tabWidget->addTab(m_dressList, "连衣裙");

    mainLayout->addWidget(tabWidget,1);

    //中间展示区
    m_view = new QGraphicsView;
    m_scene = new QGraphicsScene;
    m_scene->setSceneRect(0,0,600,700);
    m_view->setScene(m_scene);
    m_view->fitInView(m_scene->sceneRect(), Qt::KeepAspectRatio);
    m_view->setResizeAnchor(QGraphicsView::AnchorViewCenter);
    m_view->setMinimumSize(410,510);

    // 调整视图交互模式，确保能选中和拖拽物品
    m_view->setDragMode(QGraphicsView::RubberBandDrag); // 框选模式
    m_view->setMouseTracking(true);
    m_view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    m_view->setBackgroundBrush(Qt::white);
    m_view->setRenderHint(QPainter::Antialiasing);

    mainLayout->addWidget(m_view,2);

    //右侧功能区
    QWidget* rightWidget = new QWidget;
    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);
    rightLayout->setSpacing(20);

    m_scene1Btn = new QPushButton("房间");
    m_scene2Btn = new QPushButton("教室");
    m_saveBtn = new QPushButton("保存");
    m_resetBtn = new QPushButton("重置");
    m_randomBtn = new QPushButton("随机");
    m_themeCheckBox = new QCheckBox("深色主题");
    m_confirmBtn = new QPushButton("确认搭配");  // 新增


    rightLayout->addWidget(m_confirmBtn);        // 新增到布局

    rightLayout->addWidget(m_scene1Btn);
    rightLayout->addWidget(m_scene2Btn);
    rightLayout->addWidget(m_saveBtn);
    rightLayout->addWidget(m_resetBtn);
    rightLayout->addWidget(m_randomBtn);
    rightLayout->addWidget(m_themeCheckBox);
    rightLayout->addStretch();

    mainLayout->addWidget(rightWidget, 1);
}

void MainWindow::initConnections()
{
    connect(m_upcloList, &QListWidget::itemClicked, this, &MainWindow::onUpListItemClicked);
    connect(m_downcloList, &QListWidget::itemClicked, this, &MainWindow::onDownListItemClicked);
    connect(m_shoesList, &QListWidget::itemClicked, this, &MainWindow::onShoesListItemClicked);
    connect(m_dressList, &QListWidget::itemClicked, this, &MainWindow::onDressListItemClicked);

    connect(m_scene1Btn,&QPushButton::clicked,this,&MainWindow::onScene1BtnClicked);
    connect(m_scene2Btn,&QPushButton::clicked,this,&MainWindow::onScene2BtnClicked);
    connect(m_saveBtn,&QPushButton::clicked,this,&MainWindow::onSaveBtnClicked);
    connect(m_resetBtn, &QPushButton::clicked, this, &MainWindow::onResetBtnClicked);
    connect(m_randomBtn, &QPushButton::clicked, this, &MainWindow::onRandomBtnClicked);
    connect(m_themeCheckBox,&QCheckBox::toggled,this,&MainWindow::onThemeCheckBoxToggled);
    connect(m_confirmBtn, &QPushButton::clicked, this, &MainWindow::onConfirmBtnClicked);
}

void MainWindow::loadClothes()
{
    // 添加上衣（wearOffset：对齐人物上半身）
        m_clothesList.append({
            "白色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt1.png",
            "上衣",
            QPoint(0, -30),    // 拖拽时临时偏移
            QPoint(0, -50)     // 穿戴时对齐偏移（需根据实际图片调整）
        });
        m_clothesList.append({
            "蓝色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt2.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "粉色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt3.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "黄色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt4.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "牛仔外套",
            ":/upclothes/materialPackage/upclothes/jacket.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -60)     // 外套可能需要更大的偏移
        });

        // 添加下装（wearOffset：对齐人物腰部）
        m_clothesList.append({
            "运动裤",
            ":/downclothes/materialPackage/downclothes/trousers1.png",
            "下装",
            QPoint(0, 120),
            QPoint(0, 80)      // 对齐腰部
        });
        m_clothesList.append({
            "牛仔裤",
            ":/downclothes/materialPackage/downclothes/trousers2.png",
            "下装",
            QPoint(0, 120),
            QPoint(0, 80)
        });

        // 添加连衣裙（wearOffset：对齐人物全身）
        m_clothesList.append({
            "粉色连衣裙",
            ":/dress/materialPackage/dress/dress1.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });
        m_clothesList.append({
            "蓝色连衣裙",
            ":/dress/materialPackage/dress/dress2.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });
        m_clothesList.append({
            "中式连衣裙",
            ":/dress/materialPackage/dress/dress3.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });

        // 添加鞋子（wearOffset：对齐人物脚部）
        m_clothesList.append({
            "凉鞋",
            ":/shoes/materialPackage/shoes/shoes1.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)     // 对齐脚部
        });
        m_clothesList.append({
            "皮鞋",
            ":/shoes/materialPackage/shoes/shoes2.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)     // 对齐脚部
        });
        m_clothesList.append({
            "运动鞋",
            ":/shoes/materialPackage/shoes/shoes3.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)
        });

    //将服饰添加到对应的列表
    foreach(const ClothesInfo &info, m_clothesList)
    {
        QListWidgetItem *item = new QListWidgetItem;
        QPixmap pixmap(info.path);
        if(pixmap.isNull())
        {
            qWarning() << "Failed to load image:" << info.path;
            item->setIcon(QIcon::fromTheme("image-x-generic"));
        }
        else
        {
            item->setIcon(QIcon(pixmap));
        }
        item->setText(info.name);
        item->setSizeHint(QSize(100, 100));

        if (info.category == "上衣")
            m_upcloList->addItem(item);
        else if (info.category == "下装")
            m_downcloList->addItem(item);
        else if (info.category == "鞋子")
            m_shoesList->addItem(item);
        else if (info.category == "连衣裙")
            m_dressList->addItem(item);
    }
}

void MainWindow::clearCurrentClothes()
{
    //清除上衣
    if (m_upcloItem)
    {
        m_scene->removeItem(m_upcloItem);
        delete m_upcloItem;
        m_upcloItem = nullptr;
    }

    //清除下装
    if (m_downcloItem)
    {
        m_scene->removeItem(m_downcloItem);
        delete m_downcloItem;
        m_downcloItem = nullptr;
    }

    //清除连衣裙
    if (m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }

    //清除鞋子
    if (m_shoesItem)
    {
        m_scene->removeItem(m_shoesItem);
        delete m_shoesItem;
        m_shoesItem = nullptr;
    }
}

void MainWindow::addClothesToScene(const ClothesInfo &info)
{
    hideCombo();
    //先清除同类型的已有服饰
    if (info.category == "上衣")
    {
         if (m_upcloItem) {
                     m_scene->removeItem(m_upcloItem);
                     delete m_upcloItem;
                 }
                 m_upcloItem = new DragablePixmapItem(info.name); // 传入名称
                 m_scene->addItem(m_upcloItem);
                 connect(m_upcloItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "下装")
    {
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
        }
        m_downcloItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_downcloItem);
        connect(m_downcloItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "连衣裙")
    {
        if (m_dressItem)
        {
            m_scene->removeItem(m_dressItem);
            delete m_dressItem;
        }
        m_dressItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_dressItem);
        connect(m_dressItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "鞋子")
    {
        if (m_shoesItem)
        {
            m_scene->removeItem(m_shoesItem);
            delete m_shoesItem;
        }
        m_shoesItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_shoesItem);
        connect(m_shoesItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
        checkAndShowCombo();
    }

    //获取当前要显示的服饰项
    DragablePixmapItem* currentItem = nullptr;
    if (info.category == "上衣") currentItem = m_upcloItem;
    else if (info.category == "下装") currentItem = m_downcloItem;
    else if (info.category == "连衣裙") currentItem = m_dressItem;
    else if (info.category == "鞋子") currentItem = m_shoesItem;

    QPixmap pixmap(info.path);
       if (pixmap.isNull())
       {
           qWarning() << "Failed to load clothes image:" << info.path;
           return;
       }
       currentItem->setPixmap(pixmap.scaled(pixmap.size() * m_clothesScale, Qt::KeepAspectRatio, Qt::SmoothTransformation));

       if (currentItem)
          {
              QPixmap pixmap(info.path);
              if(!pixmap.isNull())
              {
                  currentItem->setPixmap(pixmap.scaled(pixmap.size() * m_clothesScale, Qt::KeepAspectRatio, Qt::SmoothTransformation));
              }
              currentItem->setPos(m_scene->sceneRect().center() + info.dragOffset);
          }

       // 设置初始位置（基于人物位置偏移）
       if (m_characterItem)
       {
           QPointF characterPos = m_characterItem->pos();
           currentItem->setPos(characterPos + info.dragOffset); // 临时拖拽位置
       }
       else
       {
           currentItem->setPos(info.dragOffset); // 若人物未加载，使用默认偏移
       }

}

//上衣列表项点击事件处理
void MainWindow::onUpListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}

//下装列表项点击事件处理
void MainWindow::onDownListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}

//鞋子列表项点击事件处理
void MainWindow::onShoesListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }

    //添加到场场景
    addClothesToScene(info);
}

//连衣裙列表项点击事件处理
void MainWindow::onDressListItemClicked(QListWidgetItem *item)
{
    // 关键修改8：选择连衣裙时隐藏上下装
        if (m_upcloItem)
        {
            m_scene->removeItem(m_upcloItem);
            delete m_upcloItem;
            m_upcloItem = nullptr;
        }
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
            m_downcloItem = nullptr;
        }

        // 加载选中的连衣裙
        ClothesInfo info = getClothesInfoByName(item->text());
        addClothesToScene(info);
}

bool MainWindow::onConfirmBtnClicked()
{
    // 检查是否有完整搭配（上衣+下装+鞋子 或 连衣裙+鞋子）
    bool hasCompleteOutfit = false;
    bool comboFound = false;

    // 检查上衣+下装+鞋子组合
    if (m_upcloItem && m_downcloItem && m_shoesItem)
    {
        hasCompleteOutfit = true;
        comboFound = checkAndShowCombo(); // 修改为返回布尔值
    }
    // 检查连衣裙+鞋子组合
    else if (m_dressItem && m_shoesItem)
    {
        hasCompleteOutfit = true;
        comboFound = checkAndShowCombo(); // 修改为返回布尔值
    }

    if (hasCompleteOutfit)
    {
        checkAndShowCombo();  // 触发合成图显示
        if (comboFound)
        {
          QMessageBox::information(this, "提示", "已生成搭配效果！");
        }
        else
        {
          QMessageBox::information(this, "提示", "搭配完成，但无特殊效果");
        }
      }
    else
    {
        QMessageBox::warning(this, "提示", "请选择完整搭配（上衣+下装+鞋子 或 连衣裙+鞋子）");
    }
     return comboFound;
}


// 实现辅助函数 getClothesInfoByName
ClothesInfo MainWindow::getClothesInfoByName(const QString &name)
{
    foreach (const ClothesInfo& info, m_clothesList)
    {
        if (info.name == name)
        {
            return info;
        }
    }
    return ClothesInfo(); // 未找到返回空
}

// 根据服饰项获取对应的ClothesInfo（辅助函数）
ClothesInfo MainWindow::getClothesInfoByItem(DragablePixmapItem* item)
{
    if (!item) return ClothesInfo();

     return getClothesInfoByName(item->name());

//        // 直接通过服饰项的类型进行精确匹配（更可靠）
//        if (item == m_upcloItem)
//        {
//            foreach (const ClothesInfo &info, m_clothesList)
//            {
//                if (info.category == "上衣")
//                {
//                    // 比较图片路径（最可靠的方式）
//                    QFileInfo itemFile(info.path);
//                    QPixmap itemPix(info.path);
//                    if (!itemPix.isNull() && item->pixmap().size() == itemPix.scaled(item->pixmap().size(), Qt::KeepAspectRatio).size())
//                    {
//                        return info;
//                    }
//                }
//            }
//        }
//        else if (item == m_downcloItem)
//        {
//            foreach (const ClothesInfo &info, m_clothesList)
//            {
//                if (info.category == "下装")
//                {
//                    QPixmap itemPix(info.path);
//                    if (!itemPix.isNull() && item->pixmap().size() == itemPix.scaled(item->pixmap().size(), Qt::KeepAspectRatio).size())
//                    {
//                        return info;
//                    }
//                }
//            }
//        }
//        else if (item == m_shoesItem)
//        {
//            foreach (const ClothesInfo &info, m_clothesList)
//            {
//                if (info.category == "鞋子")
//                {
//                    QPixmap itemPix(info.path);
//                    if (!itemPix.isNull() && item->pixmap().size() == itemPix.scaled(item->pixmap().size(), Qt::KeepAspectRatio).size())
//                    {
//                        return info;
//                    }
//                }
//            }
//        }

//        qWarning() << "无法找到匹配的服饰信息";
//        return ClothesInfo();

}


//场景一按钮点击事件处理
void MainWindow::onScene1BtnClicked()
{
    // 清除现有场景背景
       if (m_sceneItem)
       {
           m_scene->removeItem(m_sceneItem);
           delete m_sceneItem;
           m_sceneItem = nullptr;
       }

       // 设置场景1背景（房间）
       QPixmap scenePixmap(":/scenes/materialPackage/scenes/room.png");
       if (!scenePixmap.isNull())
       {
           m_sceneItem = new QGraphicsPixmapItem(scenePixmap.scaled(
                      m_scene->sceneRect().size().toSize(),
                      Qt::KeepAspectRatio,
                      Qt::SmoothTransformation));
           m_scene->addItem(m_sceneItem); // 补充添加到场景的代码
                  m_sceneItem->setZValue(-1); // 补充设置层级
       }

       // 加载人物形象
       loadCharacter();
}


void MainWindow::onScene2BtnClicked()
{
    // 清除现有场景背景
        if (m_sceneItem)
        {
            m_scene->removeItem(m_sceneItem);
            delete m_sceneItem;
            m_sceneItem = nullptr;
        }

        // 设置场景2背景（教室）
        QPixmap scenePixmap(":/scenes/materialPackage/scenes/classroom.png");
        if (!scenePixmap.isNull())
        {
            m_sceneItem = new QGraphicsPixmapItem(scenePixmap.scaled(m_scene->sceneRect().size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
            m_scene->addItem(m_sceneItem);
            m_sceneItem->setZValue(-1); // 背景在最底层
        }

        // 加载人物形象
        loadCharacter();
}

//保存按钮
void MainWindow::onSaveBtnClicked()
{
    //获取场景的截图
    QPixmap pixmap = m_view->grab();

    //弹出文件对话框，让用户选择保存路径
    QString fileName = QFileDialog::getSaveFileName(this,
            tr("保存搭配"), "",
            tr("PNG图片 (*.png);;JPEG图片 (*.jpg *.jpeg);;所有文件 (*)"));

        if (fileName.isEmpty())
        {
            return;
        }

        // 保存图片
        if (!pixmap.save(fileName))
        {
            QMessageBox::warning(this, "保存失败", "无法保存图片文件");
        }
        else
        {
            QMessageBox::information(this, "保存成功", QString("图片已保存到: %1").arg(fileName));
        }
}

//重置按钮点击事件处理
void MainWindow::onResetBtnClicked()
{

    hideCombo(); // 隐藏合成图
    clearCurrentClothes();

        // 关键修改9：重置时重新加载人物（防止被误删）
        if (!m_characterItem)
        {
            loadCharacter();
        }
}

//随机按钮点击事件处理
void MainWindow::onRandomBtnClicked()
{
    //清除当前搭配的服饰
    clearCurrentClothes();

    //获取随机数生成器
    QRandomGenerator* generator = QRandomGenerator::global();

    //随机选择上衣加下装或者连衣裙
    bool chooseDress = (generator->bounded(2) == 0)&&(m_dressList->count()>0);

    if(chooseDress)
    {
        //随机选择连衣裙
        int randomIndex = generator->bounded(m_dressList->count());
        QListWidgetItem *item = m_dressList->item(randomIndex);

        if(item)
        {
            onDressListItemClicked(item);
        }
    }
    else
    {
     // 随机选择上衣（如果有）
      if (m_upcloList->count() > 0)
      {
            int randomIndex = generator->bounded(m_upcloList->count());
             QListWidgetItem *item = m_upcloList->item(randomIndex);
             if (item)
             {
                 onUpListItemClicked(item);
             }


                // 随机选择下装（如果有）
                if (m_downcloList->count() > 0)
                {
                    int randomIndex = generator->bounded(m_downcloList->count());
                    QListWidgetItem *item = m_downcloList->item(randomIndex);
                    if (item)
                    {
                        onDownListItemClicked(item);
                    }
                }
        }
    }
    if (m_shoesList->count() > 0)
        {
            int shoeIndex = generator->bounded(m_shoesList->count());
            QListWidgetItem *shoeItem = m_shoesList->item(shoeIndex);
            if (shoeItem)
            {
                onShoesListItemClicked(shoeItem);
            }
        }
}

//主题切换事件处理
void MainWindow::onThemeCheckBoxToggled(bool checked)
{
    if (checked)
    {
          // 深色主题
            QPalette palette = qApp->palette();
            palette.setColor(QPalette::Window, QColor(53, 53, 53));
            palette.setColor(QPalette::WindowText, Qt::white);
            palette.setColor(QPalette::Base, QColor(25, 25, 25));
            palette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
            palette.setColor(QPalette::ToolTipBase, Qt::white);
            palette.setColor(QPalette::ToolTipText, Qt::white);
            palette.setColor(QPalette::Text, Qt::white);
            palette.setColor(QPalette::Button, QColor(53, 53, 53));
            palette.setColor(QPalette::ButtonText, Qt::white);
            palette.setColor(QPalette::BrightText, Qt::red);
            palette.setColor(QPalette::Link, QColor(42, 130, 218));
            palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
            palette.setColor(QPalette::HighlightedText, Qt::black);
            qApp->setPalette(palette);
            m_view->setBackgroundBrush(QColor(53, 53, 53));  // 同步视图背景
      }
    else
    {
            // 浅色主题（默认）
            qApp->setPalette(qApp->style()->standardPalette());
            m_view->setBackgroundBrush(Qt::white);  // 恢复白色背景
    }
}
// 加载人物形象到场景
void MainWindow::loadCharacter()
{
    // 先移除现有人物（如果有）
    if (m_characterItem)
    {
        m_scene->removeItem(m_characterItem);
        delete m_characterItem;
        m_characterItem = nullptr;
    }

    // 设置人物资源路径（请替换为实际路径）
    m_characterPath = ":/girl/materialPackage/cartoolgirl.png";

    QPixmap characterPixmap(m_characterPath);
    if (characterPixmap.isNull())
    {
        qWarning() << "Failed to load character image:" << m_characterPath;
        return;
    }

    // 创建人物图形项（不可拖拽）
    if (m_characterItem)
    {
        m_scene->removeItem(m_characterItem);
        delete m_characterItem;
    }
    m_characterItem = new QGraphicsPixmapItem;
    QSize scaledSize = characterPixmap.size() * m_characterScale;
        m_characterItem->setPixmap(
            characterPixmap.scaled(
                scaledSize,
                Qt::KeepAspectRatio,
                Qt::SmoothTransformation
            )
        );
        m_scene->addItem(m_characterItem);

    // 设置人物在场景中央

    //1.获取场景可视区域的中心点（即使图显示的中心）
        QPointF viewCenter = m_view->viewport()->rect().center();
        //2.将试图中心转换为场景坐标系的坐标
    QPointF sceneCentert = m_view->mapToScene(viewCenter.toPoint());

    //3.计算人物左上角的坐标：场景中心-人物自身一半尺寸
    QPointF characterTopLeft(
                sceneCentert.x() - scaledSize.width()/2,//水平方向居中
                sceneCentert.y() - scaledSize.height()/2
                );
    //设置人物位置
    m_characterItem->setPos(characterTopLeft);

}

// 检测服饰是否与人物碰撞（在mainwindow.cpp中）
void MainWindow::checkClothesCollision(DragablePixmapItem* clothesItem)
{
    if (!m_characterItem || !clothesItem) return;

    // 如果已经穿戴，不需要重复检测
    if (clothesItem->isWorn()) return;

    // 获取人物和服饰的碰撞区域（场景坐标系）
    QRectF characterRect = m_characterItem->mapRectToScene(m_characterItem->boundingRect());
    QRectF clothesRect = clothesItem->mapRectToScene(clothesItem->boundingRect());

    // 检测碰撞（重叠面积超过服饰面积的30%视为有效穿戴）
    QRectF intersection = characterRect.intersected(clothesRect);
    if (intersection.width()*intersection.height() > clothesRect.width()*clothesRect.height() * 0.3) {
        wearClothes(clothesItem); // 穿戴服饰
    }
}

// 穿戴服饰（自动对齐到人物身上）
void MainWindow::wearClothes(DragablePixmapItem* clothesItem)
{
    if (!clothesItem || m_showingCombo) return;

    clothesItem->setWorn(true);
    clothesItem->setFlag(QGraphicsItem::ItemIsMovable, false); // 穿戴后不可移动

    // 2. 获取该服饰的信息（主要是wearOffset）
    ClothesInfo info = getClothesInfoByItem(clothesItem); // 需实现这个函数
    if (m_characterItem)
        {
            QPointF charPos = m_characterItem->pos();
            clothesItem->setPos(charPos + info.wearOffset);
        }

    // 检查是否可以显示套装合成图
       checkAndShowCombo();

    // 3. 计算对齐位置（人物位置 + 穿戴偏移）
    QPointF characterPos = m_characterItem->pos();
    QPointF wearPos = characterPos + info.wearOffset;

    // 4. 固定服饰位置并设置层级（在人物上方）
    clothesItem->setPos(wearPos);
    clothesItem->setZValue(1); // 人物z=0，服饰z=1确保显示在上方

    // 5. 穿戴后禁止拖拽（可选，也可以允许微调）
    clothesItem->setFlag(QGraphicsItem::ItemIsMovable, true);
}

// 实现检查并显示套装合成图的函数
bool MainWindow::checkAndShowCombo()
{
    hideCombo(); // 先隐藏已有的合成图

    // 先确保所有单品都已穿戴
        if ((m_upcloItem && !m_upcloItem->isWorn()) ||
            (m_downcloItem && !m_downcloItem->isWorn()) ||
            (m_shoesItem && !m_shoesItem->isWorn()) ||
            (m_dressItem && !m_dressItem->isWorn())) {
            qDebug() << "有单品未穿戴，不显示合成图";

        }

       // 获取当前穿戴的服饰名称（增加调试输出）
       QString topName = m_upcloItem && m_upcloItem->isWorn() ? getClothesInfoByItem(m_upcloItem).name : "未选择";
       QString dressName = m_dressItem && m_dressItem->isWorn() ? getClothesInfoByItem(m_dressItem).name : "未选择";
       QString bottomName = m_downcloItem && m_downcloItem->isWorn() ? getClothesInfoByItem(m_downcloItem).name : "未选择";
       QString shoesName = m_shoesItem && m_shoesItem->isWorn() ? getClothesInfoByItem(m_shoesItem).name : "未选择";

       qDebug() << "当前选择 - 上衣:" << topName << "连衣裙:" << dressName << "下装:" << bottomName << "鞋子:" << shoesName;

       // 遍历所有套装查找匹配
       foreach (const OutfitCombo &combo, m_outfitCombos)
       {
           qDebug() << "检查套装:" << combo.name
                    << "要求 - 上衣:" << combo.top
                    << "连衣裙:" << combo.dress
                    << "下装:" << combo.bottom
                    << "鞋子:" << combo.shoes;

           // 匹配上衣+下装+鞋子组合（非连衣裙套装）
           if (!combo.top.isEmpty() && combo.dress.isEmpty())
           {
               if (combo.top == topName && combo.bottom == bottomName && combo.shoes == shoesName)
               {
                   qDebug() << "找到匹配的上衣+下装+鞋子套装，尝试加载图片:" << combo.comboImagePath;

                   // 尝试加载图片
                   QPixmap pixmap(combo.comboImagePath);
                   if (pixmap.isNull())
                   {
                       qWarning() << "无法加载合成图，路径错误:" << combo.comboImagePath;
                       QMessageBox::warning(this, "加载失败", "合成图资源不存在:\n" + combo.comboImagePath);
                       return false;
                   }

                   // 显示合成图
                   if (m_comboItem)
                   {
                       m_scene->removeItem(m_comboItem);
                       delete m_comboItem;
                   }
                   m_comboItem = new QGraphicsPixmapItem;
                   m_comboItem->setPixmap(pixmap.scaled(pixmap.size() * m_characterScale,
                                                      Qt::KeepAspectRatio,
                                                      Qt::SmoothTransformation));
                   m_comboItem->setPos(m_characterItem->pos());
                   m_scene->addItem(m_comboItem);

                   // 隐藏原始元素
                   if (m_characterItem) m_characterItem->hide();
                   if (m_upcloItem) m_upcloItem->hide();
                   if (m_downcloItem) m_downcloItem->hide();
                   if (m_dressItem) m_dressItem->hide();
                   if (m_shoesItem) m_shoesItem->hide();

                   m_showingCombo = true;
                   return m_showingCombo;
               }
           }
           // 匹配连衣裙+鞋子组合（连衣裙套装）
           else if (combo.top.isEmpty() && !combo.dress.isEmpty())
           {
               if (combo.dress == dressName && combo.shoes == shoesName)
               {
                   qDebug() << "找到匹配的连衣裙+鞋子套装，尝试加载图片:" << combo.comboImagePath;

                   // 尝试加载图片
                   QPixmap pixmap(combo.comboImagePath);
                   if (pixmap.isNull())
                   {
                       qWarning() << "无法加载合成图，路径错误:" << combo.comboImagePath;
                       QMessageBox::warning(this, "加载失败", "合成图资源不存在:\n" + combo.comboImagePath);
                       return false;
                   }

                   // 显示合成图
                   if (m_comboItem)
                   {
                       m_scene->removeItem(m_comboItem);
                       delete m_comboItem;
                   }
                   m_comboItem = new QGraphicsPixmapItem;
                   m_comboItem->setPixmap(pixmap.scaled(pixmap.size() * m_characterScale,
                                                      Qt::KeepAspectRatio,
                                                      Qt::SmoothTransformation));
                   m_comboItem->setPos(m_characterItem->pos());
                   m_scene->addItem(m_comboItem);

                   // 隐藏原始元素（与上衣套装逻辑一致，确保所有单品都隐藏）
                   if (m_characterItem) m_characterItem->hide();
                   if (m_upcloItem) m_upcloItem->hide();
                   if (m_downcloItem) m_downcloItem->hide();
                   if (m_dressItem) m_dressItem->hide();
                   if (m_shoesItem) m_shoesItem->hide();

                   m_showingCombo = true;
                   return m_showingCombo;
               }
           }
       }

       // 如果没有找到匹配的套装
       qDebug() << "未找到匹配的套装组合";
       QMessageBox::information(this, "提示", "未找到对应的搭配效果组合");
   }


bool MainWindow::showComboImage(const QString &imagePath)
{
    QPixmap pixmap(imagePath);
    if (pixmap.isNull())
    {
        qWarning() << "无法加载合成图，路径错误:" << imagePath;
        return false;
    }

    // 显示合成图
    if (m_comboItem)
    {
        m_scene->removeItem(m_comboItem);
        delete m_comboItem;
    }
    m_comboItem = new QGraphicsPixmapItem;
    m_comboItem->setPixmap(pixmap.scaled(pixmap.size() * m_characterScale,
                                       Qt::KeepAspectRatio,
                                       Qt::SmoothTransformation));
    m_comboItem->setPos(m_characterItem->pos());
    m_scene->addItem(m_comboItem);

    // 隐藏原始元素
    if (m_characterItem) m_characterItem->hide();
    if (m_upcloItem) m_upcloItem->hide();
    if (m_downcloItem) m_downcloItem->hide();
    if (m_dressItem) m_dressItem->hide();
    if (m_shoesItem) m_shoesItem->hide();

    m_showingCombo = true;
    return true;
}
// 实现隐藏合成图的函数
void MainWindow::hideCombo()
{
    if (!m_showingCombo) return;

    // 移除合成图
    if (m_comboItem)
    {
        m_scene->removeItem(m_comboItem);
        delete m_comboItem;
        m_comboItem = nullptr;
    }

    // 显示原始元素
    if (m_characterItem) m_characterItem->show();
    if (m_upcloItem) m_upcloItem->show();
    if (m_downcloItem) m_downcloItem->show();
    if (m_dressItem) m_dressItem->show();
    if (m_shoesItem) m_shoesItem->show();

    m_showingCombo = false;
}


void MainWindow::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    m_view->fitInView(m_scene->sceneRect(), Qt::KeepAspectRatio);
}

void MainWindow::loadOutfitCombos()
{
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "休闲套装",
        "白色T恤","","牛仔裤", "凉鞋",
        ":/combined/materialPackage/combined/T1_t2_s1.png"
    });
//    // 如果需要连衣裙套装，可以这样定义
//    m_outfitCombos.append({
//        "连衣裙套装",
//        "",           // top: 为空
//        "粉色连衣裙",  // dress: 连衣裙名称
//        "",           // bottom: 为空
//        "皮鞋",       // shoes: 鞋子名称
//        ":/combined/materialPackage/combined/dress_outfit.png"
//    });
}
